<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="安装项目介绍 创建新的对象并初始化的操作，可能会消耗很多的时间。在这种对象的初始化工作包含了一些费时的操作（例如，从一台位于20,000千米以外的主机上读出一些数据）的时候，尤其是这样。在需要大量生成这样的对象的时候，就可能会对性能造成一些不可忽略的影响。要缓解这个问题，除了选用更好的硬件和更棒的虚拟机以外，适当地采用一些能够减少对象创建次数的编码技巧，也是一种有效的对策。对象池化技术（Objec">
<meta property="og:type" content="article">
<meta property="og:title" content="Apache Commons-pool2使用入门">
<meta property="og:url" content="http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="安装项目介绍 创建新的对象并初始化的操作，可能会消耗很多的时间。在这种对象的初始化工作包含了一些费时的操作（例如，从一台位于20,000千米以外的主机上读出一些数据）的时候，尤其是这样。在需要大量生成这样的对象的时候，就可能会对性能造成一些不可忽略的影响。要缓解这个问题，除了选用更好的硬件和更棒的虚拟机以外，适当地采用一些能够减少对象创建次数的编码技巧，也是一种有效的对策。对象池化技术（Objec">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/concepts-1.jpg">
<meta property="og:image" content="http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/object-pool.png">
<meta property="og:image" content="http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/PooledObjectState.png">
<meta property="og:image" content="http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/borrow.png">
<meta property="og:image" content="http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/return-object.png">
<meta property="article:published_time" content="2021-10-01T16:00:00.000Z">
<meta property="article:modified_time" content="2021-10-02T06:53:22.921Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="第三方 Jar 整合">
<meta property="article:tag" content="池">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/concepts-1.jpg">


<link rel="canonical" href="http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/","path":"2021/10/02/Apache-Commons-pool2使用入门/","title":"Apache Commons-pool2使用入门"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Apache Commons-pool2使用入门 | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%89%E8%A3%85"><span class="nav-number">1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%A1%B9%E7%9B%AE%E4%BB%8B%E7%BB%8D"><span class="nav-number">2.</span> <span class="nav-text">项目介绍</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Maven-%E4%BE%9D%E8%B5%96"><span class="nav-number">2.1.</span> <span class="nav-text">Maven 依赖</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%8E%A5%E5%8F%A3%E8%AE%BE%E8%AE%A1"><span class="nav-number">3.</span> <span class="nav-text">接口设计</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ObjectPool"><span class="nav-number">3.1.</span> <span class="nav-text">ObjectPool</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PooledObject"><span class="nav-number">3.2.</span> <span class="nav-text">PooledObject</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PooledObjectFactory"><span class="nav-number">3.3.</span> <span class="nav-text">PooledObjectFactory</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%B8%E7%94%A8%E7%9A%84%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="nav-number">4.</span> <span class="nav-text">常用的实现类</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#GenericObjectPool"><span class="nav-number">4.1.</span> <span class="nav-text">GenericObjectPool</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#borrowObject"><span class="nav-number">4.2.</span> <span class="nav-text">borrowObject</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#returnObject"><span class="nav-number">4.3.</span> <span class="nav-text">returnObject</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DefaultPooledObject"><span class="nav-number">4.4.</span> <span class="nav-text">DefaultPooledObject</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E4%BB%8B%E7%BB%8D"><span class="nav-number">5.</span> <span class="nav-text">使用介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8F%82%E8%80%83%E9%93%BE%E6%8E%A5"><span class="nav-number">6.</span> <span class="nav-text">参考链接</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Apache Commons-pool2使用入门 | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Apache Commons-pool2使用入门
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2021-10-02 00:00:00 / 修改时间：14:53:22" itemprop="dateCreated datePublished" datetime="2021-10-02T00:00:00+08:00">2021-10-02</time>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><h2 id="项目介绍"><a href="#项目介绍" class="headerlink" title="项目介绍"></a>项目介绍</h2><blockquote>
<p>创建新的对象并初始化的操作，可能会消耗很多的时间。在这种对象的初始化工作包含了一些费时的操作（例如，从一台位于20,000千米以外的主机上读出一些数据）的时候，尤其是这样。在需要大量生成这样的对象的时候，就可能会对性能造成一些不可忽略的影响。要缓解这个问题，除了选用更好的硬件和更棒的虚拟机以外，适当地采用一些能够减少对象创建次数的编码技巧，也是一种有效的对策。对象池化技术（Object Pooling）就是这方面的著名技巧，而Jakarta Commons Pool组件则是处理对象池化的得力外援。</p>
</blockquote>
<p>Commons Pool组件提供了一整套用于实现对象池化的框架，以及若干种各具特色的对象池实现，可以有效地减少处理对象池化时的工作量，为其它重要的工作留下更多的精力和时间</p>
<p>Apache Common-pool2完全重写了的对象池的实现，显著的提升了性能和可伸缩性，特别是在高并发加载的情况下。2.0 版本包含可靠的实例跟踪和池监控。</p>
<h3 id="Maven-依赖"><a href="#Maven-依赖" class="headerlink" title="Maven 依赖"></a>Maven 依赖</h3><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">properties</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">commons-pool2.version</span>&gt;</span>2.11.1<span class="tag">&lt;/<span class="name">commons-pool2.version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.apache.commons<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-pool2<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;commons-pool2.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h2 id="接口设计"><a href="#接口设计" class="headerlink" title="接口设计"></a>接口设计</h2><p><code>Apache Commons Pool</code>实现了<strong>对象池</strong>的功能。定义了对象的生成、销毁、激活、钝化等操作及其状态转换，并提供几个默认的对象池实现。<br>在讲述其实现原理前，先提一下其中有几个重要的对象：</p>
<ul>
<li><p>Object Pool（对象池）。</p>
</li>
<li><p>PooledObject（池对象）。</p>
</li>
<li><p>PooledObjectFactory（池对象工厂）。</p>
</li>
</ul>
<p>三种之间的关系图：</p>
<p><img src="/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/concepts-1.jpg" alt="关系图"></p>
<p>下面分别详细讲解它们的实现。</p>
<p>（以下三个均为接口，位于 org.apache.commons.pool2）</p>
<h3 id="ObjectPool"><a href="#ObjectPool" class="headerlink" title="ObjectPool"></a>ObjectPool</h3><p>Object Pool负责管理PooledObject，如：借出对象，返回对象，校验对象，有多少激活对象，有多少空闲对象。</p>
<p>以下为类图结构，有几个默认的实现类可以直接使用。</p>
<ul>
<li><p>GenericObjectPool。</p>
</li>
<li><p>ProsiedObjectPool。</p>
</li>
<li><p>SoftReferenceObjectPool。</p>
</li>
</ul>
<p><img src="/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/object-pool.png" alt="Object Pool （对象池）"> </p>
<table>
<thead>
<tr>
<th align="left">方法</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">borrowObject</td>
<td align="left">从池中借出一个对象。要么调用PooledObjectFactory.makeObject方法创建，要么对一个空闲对象使用PooledObjectFactory.activeObject进行激活，然后使用PooledObjectFactory.validateObject方法进行验证后再返回</td>
</tr>
<tr>
<td align="left">returnObject</td>
<td align="left">将一个对象返还给池。根据约定：对象必须 是使用borrowObject方法从池中借出的</td>
</tr>
<tr>
<td align="left">invalidateObject</td>
<td align="left">废弃一个对象。根据约定：对象必须 是使用borrowObject方法从池中借出的。通常在对象发生了异常或其他问题时使用此方法废弃它</td>
</tr>
<tr>
<td align="left">addObject</td>
<td align="left">使用工厂创建一个对象，<strong>钝化</strong>并且将它放入空闲对象池</td>
</tr>
<tr>
<td align="left">getNumberIdle</td>
<td align="left">返回池中空闲的对象数量。有可能是池中可供借出对象的近似值。如果这个信息无效，返回一个负数</td>
</tr>
<tr>
<td align="left">getNumActive</td>
<td align="left">返回从借出的对象数量。如果这个信息不可用，返回一个负数</td>
</tr>
<tr>
<td align="left">clear</td>
<td align="left">清除池中的所有空闲对象，释放其关联的资源（可选）。清除空闲对象必须使用PooledObjectFactory.destroyObject方法，池可用。</td>
</tr>
<tr>
<td align="left">close</td>
<td align="left">关闭池并释放关联的资源，池不可用。</td>
</tr>
</tbody></table>
<h3 id="PooledObject"><a href="#PooledObject" class="headerlink" title="PooledObject"></a>PooledObject</h3><p>用于封装对象（如：线程、数据库连接、TCP连接），将其包裹成可被池管理的对象。</p>
<p>此类的实现必须是线程安全的。</p>
<p>提供了两个默认的池对象实现：</p>
<ul>
<li>DefaultPoolObject。用于非软引用的普通对象。</li>
<li>PooledSoftReference。用于软引用的对象。</li>
</ul>
<p>在开发连接池、线程池等组件时，需要根据实际情况重载5个方法：startEvictionTest、endEvictionTest、allocate、deallocate和invalidate，用于在不同的场景下修改被包裹对象的内部状态。 </p>
<p>此接口的重要的方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获得目标对象</span></span><br><span class="line">T <span class="title function_">getObject</span><span class="params">()</span>;</span><br><span class="line"><span class="comment">// 获取PooledObject的状态</span></span><br><span class="line">PooledObjectState <span class="title function_">getState</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">boolean</span> <span class="title function_">startEvictionTest</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line"><span class="type">boolean</span> <span class="title function_">endEvictionTest</span><span class="params">(Deque&lt;PooledObject&lt;T&gt;&gt; idleQueue)</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 分配对象。 如果原始状态为 IDLE, 则返回 true</span></span><br><span class="line"><span class="type">boolean</span> <span class="title function_">allocate</span><span class="params">()</span>; </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 如果当前已ALLOCATED ，则取消分配对象并将其设置为IDLE 。</span></span><br><span class="line"><span class="comment">// 如果状态为ALLOCATED则为true 。</span></span><br><span class="line"><span class="type">boolean</span> <span class="title function_">deallocate</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">invalidate</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">PooledObjectState <span class="title function_">getState</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">markAbandoned</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> <span class="title function_">markReturning</span><span class="params">()</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">... 省略其他方法</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>



<p>PooledObject有多种状态，在不同的环节或经过处理后状态会发生变化。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> org.apache.commons.pool2;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> <span class="title class_">PooledObjectState</span> &#123;</span><br><span class="line">    IDLE, <span class="comment">// 	位于队列中，未使用</span></span><br><span class="line">  </span><br><span class="line">    ALLOCATED, <span class="comment">// 已被分配，正在使用</span></span><br><span class="line">  </span><br><span class="line">    EVICTION,  <span class="comment">// 位于队列中，当前正在测试，可能会被回收到队列</span></span><br><span class="line">  </span><br><span class="line">    EVICTION_RETURN_TO_HEAD, <span class="comment">// 不在队列中，目前正在测试是否可能被驱逐。 </span></span><br><span class="line">  </span><br><span class="line">    VALIDATION, <span class="comment">// 位于队列中，当前正在验证</span></span><br><span class="line">  </span><br><span class="line">    VALIDATION_PREALLOCATED, <span class="comment">// 不在队列中，当前正在验证。当对象从池中被借出，在配置了testOnBorrow的情况下，对象从队列移除和进行预分配的时候会进行验证</span></span><br><span class="line">  </span><br><span class="line">    VALIDATION_RETURN_TO_HEAD, <span class="comment">// 不在队列中，正在进行验证。从池中借出对象时，从队列移除对象时会先进行测试。返回到队列头部的时候应该做一次完整的验证</span></span><br><span class="line">  </span><br><span class="line">    INVALID, <span class="comment">// 	回收或验证失败，【即将/已经】 销毁</span></span><br><span class="line">  </span><br><span class="line">    ABANDONED, <span class="comment">// 视为放弃，无效</span></span><br><span class="line">  </span><br><span class="line">    RETURNING <span class="comment">// 返还到池中</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>状态转换如下图：</p>
<p><img src="/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/PooledObjectState.png" alt="PooledObjectState"></p>
<h3 id="PooledObjectFactory"><a href="#PooledObjectFactory" class="headerlink" title="PooledObjectFactory"></a>PooledObjectFactory</h3><p>一个定义生命周期方法的接口，用于由ObjectPool提供服务的实例。</p>
<p>PooledObjectFactory必须实现线程安全。</p>
<p>Commons pool2 定义了抽象工厂<code>BasePooledObjectFactory</code>，使用者应该继承这个抽象类实现自己的池化工厂。</p>
<table>
<thead>
<tr>
<th align="left">方法</th>
<th align="left">描述</th>
</tr>
</thead>
<tbody><tr>
<td align="left">makeObject</td>
<td align="left">每当需要新实例时都会调用makeObject 。</td>
</tr>
<tr>
<td align="left">activateObject</td>
<td align="left">每一个钝化（passivated）的ObjectPool实例从池中借出（borrowed）前调用。</td>
</tr>
<tr>
<td align="left">validateObject</td>
<td align="left">可能用于从池中借出对象时，对处于激活（activated）状态的ObjectPool实例进行测试确保它是有效的。也有可能在ObjectPool实例返还池中进行钝化前调用进行测试是否有效。它只对处于激活状态的实例调用。</td>
</tr>
<tr>
<td align="left">passivateObject</td>
<td align="left">当实例返还池中的时候调用。</td>
</tr>
<tr>
<td align="left">destroyObject</td>
<td align="left">当实例从池中被清理出去丢弃的时候调用。</td>
</tr>
</tbody></table>
<h2 id="常用的实现类"><a href="#常用的实现类" class="headerlink" title="常用的实现类"></a>常用的实现类</h2><h3 id="GenericObjectPool"><a href="#GenericObjectPool" class="headerlink" title="GenericObjectPool"></a>GenericObjectPool</h3><h3 id="borrowObject"><a href="#borrowObject" class="headerlink" title="borrowObject"></a><code>borrowObject</code></h3><p>下面是GenericObjectPool中borrowObject方法的逻辑实现，有阻塞式和非阻塞式两种获取对象的模式。<br>默认情况下是阻塞的（你可以传入配置类更改这一行为）。</p>
<p><img src="/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/borrow.png" alt="borrow"></p>
<h3 id="returnObject"><a href="#returnObject" class="headerlink" title="returnObject"></a><code>returnObject</code></h3><p>下面是GenericObjectPool中returnObject方法的逻辑实现，在这里实现的FIFO（先进先出）和LIFO（后进先出）。</p>
<p><img src="/2021/10/02/Apache-Commons-pool2%E4%BD%BF%E7%94%A8%E5%85%A5%E9%97%A8/return-object.png" alt="return-object.png"></p>
<h3 id="DefaultPooledObject"><a href="#DefaultPooledObject" class="headerlink" title="DefaultPooledObject"></a>DefaultPooledObject</h3><h2 id="使用介绍"><a href="#使用介绍" class="headerlink" title="使用介绍"></a>使用介绍</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">Object</span> <span class="variable">obj</span> <span class="operator">=</span> <span class="literal">null</span>;</span><br><span class="line">  </span><br><span class="line">   <span class="keyword">try</span> &#123;</span><br><span class="line">       obj = pool.borrowObject();</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           <span class="comment">//...use the object...</span></span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           <span class="comment">// invalidate the object</span></span><br><span class="line">           pool.invalidateObject(obj);</span><br><span class="line">           <span class="comment">// do not return the object to the pool twice</span></span><br><span class="line">           obj = <span class="literal">null</span>;</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           <span class="comment">// make sure the object is returned to the pool</span></span><br><span class="line">           <span class="keyword">if</span> (<span class="literal">null</span> != obj) &#123;</span><br><span class="line">               pool.returnObject(obj);</span><br><span class="line">          &#125;</span><br><span class="line">       &#125;</span><br><span class="line">   &#125; <span class="keyword">catch</span>(Exception e) &#123;</span><br><span class="line">         <span class="comment">// failed to borrow an object</span></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>


<h2 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h2><p><a target="_blank" rel="noopener" href="http://commons.apache.org/proper/commons-pool/">Apache Commons Pool</a></p>
<p><a target="_blank" rel="noopener" href="http://aofengblog.com/2014/08/06/Apache-Commons-Pool2-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">Apache Commons Pool2 源码分析</a></p>
<p>注：插图来源于<a target="_blank" rel="noopener" href="http://aofengblog.com/2014/08/06/Apache-Commons-Pool2-%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/">http://aofengblog.com/</a></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/%E7%AC%AC%E4%B8%89%E6%96%B9-Jar-%E6%95%B4%E5%90%88/" rel="tag"># 第三方 Jar 整合</a>
              <a href="/tags/%E6%B1%A0/" rel="tag"># 池</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/10/02/%E4%BB%A3%E7%90%86%E6%A8%A1%E5%BC%8F%E3%80%81Java%E4%B8%AD%E7%9A%84%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86%E3%80%81Proxy%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90%E3%80%81%E5%AE%9E%E4%BE%8B%E5%88%86%E6%9E%90/" rel="prev" title="代理模式、Java中的动态代理、Proxy源码分析、实例分析">
                  <i class="fa fa-chevron-left"></i> 代理模式、Java中的动态代理、Proxy源码分析、实例分析
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/10/04/MongoDB%E5%85%A5%E9%97%A8/" rel="next" title="M1 MacOS 下使用Brew安装MongoDB、入门概念">
                  M1 MacOS 下使用Brew安装MongoDB、入门概念 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
